package com.yc.cloud.socket.server;

import com.yc.cloud.socket.service.SocketServer;
import com.yc.cloud.socket.utils.SocketSessionCacheUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * @author 杨智杰
 * @since 2021/9/22 14:03
 */
@Component
@ServerEndpoint(value = "/socket")
public class WebSocketServer {

    public static SocketServer socketServer;

    /**
     * 连接建立后触发的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        SocketSessionCacheUtil.put(session.getId(), session);
        socketServer.onOpen(session);
    }

    /**
     * 连接关闭后触发的方法
     */
    @OnClose
    public void onClose(Session session) {
        socketServer.onClose(session);
        SocketSessionCacheUtil.remove(session.getId());
    }

    /**
     * 接收到客户端消息时触发的方法
     */
    @OnMessage
    public void onMessage(Session session, String params) {
        socketServer.onMessage(session, params);
    }

    /**
     * 发生错误时触发的方法
     */
    @OnError
    public void onError(Session session, Throwable error) {
        socketServer.onError(session, error);
    }

    /**
     * 发送消息
     */
    @SneakyThrows
    public void sendMessage(Session session, Object data) {
        socketServer.sendMessage(session, data);
    }

}
